package com.yami.shop.rights.common.listener;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yami.shop.bean.event.AddRightsExternalEvent;
import com.yami.shop.rights.common.model.ProdRightsExternalData;
import com.yami.shop.rights.common.service.ProdRightsExternalDataService;
import com.yami.shop.security.common.util.AuthUserContext;
import com.yami.shop.service.AttachFileService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component("AddRightExternalListener")
@AllArgsConstructor
public class AddRightExternalListener {

    @Autowired
    private AttachFileService attachFileService;
    @Autowired
    private ProdRightsExternalDataService prodRightsExternalService;

    @EventListener(AddRightsExternalEvent.class)
    public void getProdRights(AddRightsExternalEvent event) {
        if(ObjectUtil.isEmpty(event.getExternalCode())){
            return;
        }
        String[] externalCodes = event.getExternalCode().split(",");
        List<ProdRightsExternalData> prodRightsExternals = new ArrayList<>();
        for (String externalCode : externalCodes) {
            ProdRightsExternalData prodRightsExterna = new ProdRightsExternalData();
            prodRightsExterna.setExternalId(event.getRightId());
            prodRightsExterna.setShopId(AuthUserContext.get().getShopId());
                // 生成二维码图片
//                QrConfig config = new QrConfig(300, 300);
//                BufferedImage qrgenerate = QrCodeUtil.generate(externalCode, config);
//                //保存图片
//                ByteArrayOutputStream qrOutputStream = new ByteArrayOutputStream();
//                ImageIO.write(qrgenerate, "jpg", qrOutputStream);
//                MultipartFile ossMultipartFile = new OssMultipartFile("111.jpg", ".jpg", qrOutputStream.toByteArray());
//                String fileName = attachFileService.uploadFile(ossMultipartFile.getBytes(), UUID.fastUUID() + ".jpg");
//                prodRightsExterna.setQrCode(fileName);
                prodRightsExterna.setCode(externalCode);
                prodRightsExterna.setType("1");
            prodRightsExternals.add(prodRightsExterna);
        }
        // 删除旧数据
        QueryWrapper<ProdRightsExternalData> deleteQuery =  new QueryWrapper<>();
        deleteQuery.eq("external_id",event.getRightId());
        prodRightsExternalService.remove(deleteQuery);
        // 保存数据
        prodRightsExternalService.saveBatch(prodRightsExternals);
    }

}
